﻿using System;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Windows.Forms;

namespace LibraryLogin
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
            Hide();
            Login();
        }

        private void Login()
        {
            if (Connected())
            {
                //if (System.Diagnostics.EventLog.SourceExists("LibraryLogin"))
                //{
                //    System.Diagnostics.EventLog.CreateEventSource("LibraryLogin", "Application");
                //}
                try
                {
                    ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallback;
                    string body = "buttonClicked=4&err_flag=0&err_msg=&info_flag=0&info_msg=&redirect_url=&email=a@a.c";
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://1.1.1.1/login.html");
                    req.Accept = "text/html, application/xhtml+xml, */*";
                    req.AllowAutoRedirect = false;
                    req.ContentLength = body.Length;
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.KeepAlive = true;
                    req.Method = "POST";
                    req.Referer = "https://1.1.1.1/login.html";
                    req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
                    req.Headers.Add("Accept-Encoding: gzip, deflate");
                    req.Headers.Add("Accept-Language: en-US");
                    StreamWriter sw = new StreamWriter(req.GetRequestStream());
                    sw.Write(body);
                    sw.Close();
                    HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                    if (res.StatusCode == HttpStatusCode.OK)
                    {
                        StreamReader sr = new StreamReader(res.GetResponseStream());
                        string resString = sr.ReadToEnd();
                        if (resString.Contains("You can now use all our regular network services over the wireless network."))
                        {
                            nIcon.ShowBalloonTip(100, "Success!", "Successfully logged into MCC Library Wireless", ToolTipIcon.Info);
                            //System.Diagnostics.EventLog.WriteEntry("LibraryLogin", "Successfully logged into MCC Library Wireless", System.Diagnostics.EventLogEntryType.Information);
                        }
                        else
                        {
                            nIcon.ShowBalloonTip(100, "Failure!", "Failed to log into MCC Library Wireless", ToolTipIcon.Error);
                            //System.Diagnostics.EventLog.WriteEntry("LibraryLogin", "MCC Library Wireless returned a failure to login for unknown reasons.", System.Diagnostics.EventLogEntryType.Warning);
                        }
                    }
                    else
                    {
                        nIcon.ShowBalloonTip(100, "Failure!", "Failed to log into MCC Library Wireless", ToolTipIcon.Error);
                        //System.Diagnostics.EventLog.WriteEntry("LibraryLogin", "MCC Library Wireless returned a failure to login for unknown reasons.", System.Diagnostics.EventLogEntryType.Warning);
                    }
                }
                catch (WebException wex)
                {
                    if (wex.Message != "Unable to connect to the remote server")
                    {
                        nIcon.ShowBalloonTip(100, "Failure!", "Failed to log into MCC Library Wireless", ToolTipIcon.Error);
                        //System.Diagnostics.EventLog.WriteEntry("LibraryLogin", ex.Message + "\n\n" + ex.Source + "\n\n" + ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
                    }
                }
                catch (Exception ex)
                {
                    nIcon.ShowBalloonTip(100, "Failure!", "Failed to log into MCC Library Wireless", ToolTipIcon.Error);
                    //System.Diagnostics.EventLog.WriteEntry("LibraryLogin", ex.Message + "\n\n" + ex.Source + "\n\n" + ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);
                }
            }
        }

        void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
        {
            if (e.IsAvailable)
            {
                Login();
            }
        }

        private static bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        private void CloseMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private static bool Connected()
        {
            try
            {
                foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
                {
                    IPInterfaceProperties prop = ni.GetIPProperties();
                    if (prop.DnsSuffix == "MCC-LIB.COM")
                    {
                        return true;
                    }
                }
            }
            catch
            {
            }
            return false;
        }

        private void LogOnMenuItem_Click(object sender, EventArgs e)
        {
            Login();
        }

    }
}
